const { compileFile } = require("bytenode");
const fs = require('fs')
const path = require('path')
const { RawSource } = require('webpack-sources')
const bytenode = require("bytenode");

class BytenodePlugins {
  getMainJsCode() {
    return `require('bytenode') \n require('./main.jsc')`
  }

  apply(compiler) {
    compiler.hooks.done.tapAsync('BytenodePlugins', (compilation, cb) => {
      bytenode.compileFile({
        filename: path.join(__dirname, '../dist/main.js'),
        // output: path.join(__dirname, 'dist/main.jsc'),
        compileAsModule: true,
        electron: true,
      }).then((res) => {
        fs.unlink(path.join(__dirname, '../dist/main.js'), () => {


          fs.writeFileSync(path.join(__dirname, '../dist/main.js'), this.getMainJsCode())
          cb()
        })
      })


      // if (compilation.assets['main.js']) {
      //   const source = compilation.assets['main.js'].source()
      //   const mainCode = this.getMainJsCode()
      //
      //   compilation.assets['main.js'] = new RawSource(mainCode)
      //
      //   compileElectronCode(source).then(res => {
      //     fs.writeFileSync(path.join(__dirname, '../dist/main.jsc'), res)
      //     cb()
      //   })
      // }
    })
  }
}

module.exports = BytenodePlugins